package cevent.source.cloudcenter.server.service;

import cevent.source.cloudcenter.server.domain.Product;
import cevent.source.cloudcenter.server.domain.ProductExample;
import cevent.source.cloudcenter.server.dto.*;
import cevent.source.cloudcenter.server.enums.*;
import cevent.source.cloudcenter.server.mapper.ProductMapper;
import cevent.source.cloudcenter.server.util.DuplicateUtil;
import cevent.source.cloudcenter.server.util.UUID8Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author cevent
 * @description 产品表服务层
 */
@Service
public class ProductService {
    private static final Logger LOG = LoggerFactory.getLogger(ProductService.class);
    @Resource
    private ProductMapper productMapper;

    //1.无分页列表查询：dto获取domain参数
    public List<ProductDto> productDtoList() {
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria=productExample.createCriteria();
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        productExample.setOrderByClause("sort asc");
        List<Product> productList = productMapper.selectByExampleWithBLOBs(productExample);
        List<ProductDto> productDtoList = new ArrayList<ProductDto>();
        for (int i = 0; i < productList.size(); i++) {
            Product product = productList.get(i);
            List<String> keyword = Arrays.asList(product.getSeoKeyword().split(";"));
            List<String> picList=Arrays.asList(product.getPicList().split(";"));
            //json字符串转换java对象
            List<ProductPrivilegeDescDto> privilegeDescDtoList=new ArrayList<>();

            if(!StringUtils.isEmpty(product.getPrivilegeDesc())){
                List<String> privilegeDescList=Arrays.asList(product.getPrivilegeDesc().split(";"));
                for(String privilegeDesc:privilegeDescList){
                    JSONObject jsonObject= JSON.parseObject(privilegeDesc);
                    ProductPrivilegeDescDto privilegeDescDto=JSONObject.toJavaObject(jsonObject,ProductPrivilegeDescDto.class);
                    privilegeDescDtoList.add(privilegeDescDto);
                }
            }
            ProductDto productDto = new ProductDto();
            //复制拷贝(source,target)
            BeanUtils.copyProperties(product, productDto);
            productDto.setSeoKeyword(keyword);
            productDto.setPicList(picList);
            productDto.setProductPrivilegeDescDtos(privilegeDescDtoList);
            productDtoList.add(productDto);
        }
        return productDtoList;
    }

    /*2.分页查询：pageDto保存数据
        list数据集合：listPageData
        当前页码：currentPage
        每页行数：size
        总计函数：totalSize
        前端可返回pageDto，无需返回值
     */
    public void getProductPageDtoList(PageDto pageDto) {
        //1.分页设置（前端传入当前页和每页行数params），起始页，每页行数size
        PageHelper.startPage(pageDto.getCurrentPage(), pageDto.getSize());

        ProductExample productExample = new ProductExample();

        productExample.setOrderByClause("sort asc");

        List<Product> productList = productMapper.selectByExampleWithBLOBs(productExample);
        //2.将mapper查询结果复制到pageInfo
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        //3.pageInfo计算处理处理=>后分页的总行数set到pageDto做记录
        pageDto.setTotalSize(pageInfo.getTotal());

        List<ProductDto> productDtoList = new ArrayList<>();
        productList.stream().forEach(product -> {
            List<String> keyword = Arrays.asList(product.getSeoKeyword().split(";"));
            List<String> picList=Arrays.asList(product.getPicList().split(";"));
            //json字符串转换java对象
            List<ProductPrivilegeDescDto> privilegeDescDtoList=new ArrayList<>();

            if(!StringUtils.isEmpty(product.getPrivilegeDesc())){
                List<String> privilegeDescList=Arrays.asList(product.getPrivilegeDesc().split(";"));
                for(String privilegeDesc:privilegeDescList){
                    JSONObject jsonObject= JSON.parseObject(privilegeDesc);
                    ProductPrivilegeDescDto privilegeDescDto=JSONObject.toJavaObject(jsonObject,ProductPrivilegeDescDto.class);
                    privilegeDescDtoList.add(privilegeDescDto);
                }
            }

            ProductDto productDto = new ProductDto();
            productDto.setSeoKeyword(keyword);
            productDto.setPicList(picList);
            productDto.setProductPrivilegeDescDtos(privilegeDescDtoList);
            BeanUtils.copyProperties(product, productDto);
            productDtoList.add(productDto);
        });

        pageDto.setListPageData(productDtoList);

    }

    //3.新增、修改product，将传入的id转为product对象本身
    public void save(ProductDto productDto) {
        List<String> seoKey = productDto.getSeoKeyword();
        StringBuilder sb = new StringBuilder();
        for (String item : seoKey) {
            sb.append(item + ";");
        }
        String seoKeyword = sb.toString();
        List<String> picList = productDto.getPicList();
        StringBuilder sbp = new StringBuilder();
        for (String item : picList) {
            sbp.append(item + ";");
        }
        String pics = sbp.toString();

        List<ProductPrivilegeDescDto> privilegeDescDtoList=new ArrayList<>();
        StringBuilder privilegeDesc=new StringBuilder();
        if(productDto.getProductPrivilegeDescDtos()!=null){
            LOG.info("接收到的getProductPrivilegeDescDtos：{}",productDto.getProductPrivilegeDescDtos());
            for(ProductPrivilegeDescDto privilegeDescDto:productDto.getProductPrivilegeDescDtos()){
                LOG.info("转换后的privilegeDescDto:{}",privilegeDescDto);
                JSONObject jsonObject=(JSONObject) JSONObject.toJSON(privilegeDescDto);
                String jsonStr=jsonObject.toJSONString();
                privilegeDesc.append(jsonStr+";");
            }
        }
        String privilegeStr=privilegeDesc.toString();
        Product product = DuplicateUtil.copy(productDto, Product.class);
        product.setSeoKeyword(seoKeyword);
        product.setPicList(pics);
        product.setPrivilegeDesc(privilegeStr);
        if (StringUtils.isEmpty(productDto.getUniId())) {
            this.insert(product);
        } else {
            this.update(product);
        }

    }

    public List<String> savePicList(ModulePicPathDto modulePicPathDto) {
        Product product = productMapper.selectByPrimaryKey(modulePicPathDto.getModuleId());
        List<String> picList = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        if (!StringUtils.isEmpty(product.getPicList())) {
            picList = Arrays.asList(product.getPicList().split(";"));
            for (String item : picList) {
                sb.append(item+";");
            }
        }
        sb.append(modulePicPathDto.getPicPath());
        String pics = sb.toString();
        product.setPicList(pics);
        productMapper.updateByPrimaryKeyWithBLOBs(product);
        //更新完毕，返回list
        List<String> pic = getPicList(modulePicPathDto.getModuleId());
        return pic;
    }

    private List<String> getPicList(String moduleId) {
        Product product = productMapper.selectByPrimaryKey(moduleId);
        List<String> pics = Arrays.asList(product.getPicList().split(";"));
        return pics;
    }

    //4.删除模块
    public void delete(String uniId) {
        ProductExample productExample = new ProductExample();
        productMapper.deleteByPrimaryKey(uniId);
    }

    //5.向外暴露dto，不暴露实体类：插入数据
    private void insert(Product product) {
        product.setUniId(UUID8Util.getShortUUID());
        if (product.getModuleId() == null) {
            product.setModuleId("0");
        }
        if (product.getVideoCharge() == null) {
            product.setVideoCharge(VideoChargeEnum.FREE.getCode());
        }
        if (product.getVideoType() == null) {
            product.setVideoType(VideoTypeEnum.VIDEO_YM_PROPAGANDA.getCode());
        }
        if (product.getVideoUserId() == null) {
            product.setVideoUserId("0");
        }
        if (product.getTypeId() == null) {
            product.setTypeId(ProductTypeEnum.PRODUCT_GENERAL_MERCHANDISE.getCode());
        }
        if (product.getLevel() == null) {
            product.setLevel(LevelEnum.ONE.getCode());
        }

        try {
            Date now = new Date();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt = (int) (time / 1000);
            product.setCreateTime(now);
            product.setUpdateTime(now);
            product.setiCreateTime(timeInt);
            product.setiUpdateTime(timeInt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        productMapper.insertSelective(product);
    }

    //6.更新模块
    private void update(Product product) {
        try {
            Date now = new Date();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt = (int) (time / 1000);

            product.setUpdateTime(now);
            product.setiUpdateTime(timeInt);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        productMapper.updateByPrimaryKeySelective(product);
    }

    //客户端首页产品数据获取
    public List<ProductDto> getIndexProduct() {
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andIndexShowEqualTo(PorductIndexShowEnum.SHOW.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        productExample.setOrderByClause("sort asc");
        List<Product> productList = productMapper.selectByExampleWithBLOBs(productExample);

        List<ProductDto> productDtoList = new ArrayList<ProductDto>();
        for (int i = 0; i < productList.size(); i++) {
            Product product = productList.get(i);
            List<String> keyword = Arrays.asList(product.getSeoKeyword().split(";"));
            List<String> picList = Arrays.asList(product.getPicList().split(";"));
            //json字符串转换java对象
            List<ProductPrivilegeDescDto> privilegeDescDtoList = new ArrayList<>();

            if (!StringUtils.isEmpty(product.getPrivilegeDesc())) {
                List<String> privilegeDescList = Arrays.asList(product.getPrivilegeDesc().split(";"));
                for (String privilegeDesc : privilegeDescList) {
                    JSONObject jsonObject = JSON.parseObject(privilegeDesc);
                    ProductPrivilegeDescDto privilegeDescDto = JSONObject.toJavaObject(jsonObject, ProductPrivilegeDescDto.class);
                    privilegeDescDtoList.add(privilegeDescDto);
                }
            }
            ProductDto productDto = new ProductDto();
            //复制拷贝(source,target)
            BeanUtils.copyProperties(product, productDto);
            productDto.setSeoKeyword(keyword);
            productDto.setPicList(picList);
            productDto.setProductPrivilegeDescDtos(privilegeDescDtoList);
            productDtoList.add(productDto);
        }
        return productDtoList;
    }
    //客户端：根据typeId查询product列表
    public void getProductPageListByTypeId(PageSelectDto pageSelectDto){
        //获取当前页和大小
        PageHelper.startPage(pageSelectDto.getCurrentPage(),pageSelectDto.getSize());
        //获取基础数据
        ProductExample productExample=new ProductExample();
        ProductExample.Criteria criteria=productExample.createCriteria();
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        criteria.andTypeIdEqualTo(pageSelectDto.getTypeId());
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        productExample.setOrderByClause("sort asc");
        List<Product> productList=productMapper.selectByExampleWithBLOBs(productExample);
        LOG.info("查询到的productList：{}",productList);
        //存入pageInfo
        PageInfo<Product> productPageInfo=new PageInfo<>(productList);
        //pageInfo计算总分页数，存入pageSelectDto
        pageSelectDto.setTotalSize(productPageInfo.getTotal());
        List<ProductDto> productDtoList=new ArrayList<>();
        productList.stream().forEach(product -> {
            List<String> picList=new ArrayList<>();
            List<ProductPrivilegeDescDto> privilegeDescDtoList=new ArrayList<>();
            //1.图片转换
            if(!StringUtils.isEmpty(product.getPicList())){
                picList=Arrays.asList(product.getPicList().split(";"));
            }
            //2.jsonObj转换privilegeDesc产品权限描述
            if(!StringUtils.isEmpty(product.getPrivilegeDesc())){
                List<String> privilegeDescList=Arrays.asList(product.getPrivilegeDesc().split(";"));
                for(String privilegeDescStr:privilegeDescList){
                    ProductPrivilegeDescDto productPrivilegeDescDto=new ProductPrivilegeDescDto();
                    JSONObject jsonObject=JSONObject.parseObject(privilegeDescStr);
                    productPrivilegeDescDto=JSONObject.toJavaObject(jsonObject,ProductPrivilegeDescDto.class);
                    privilegeDescDtoList.add(productPrivilegeDescDto);
                }

            }
            ProductDto productDto=DuplicateUtil.copy(product,ProductDto.class);
            productDto.setPicList(picList);
            productDto.setProductPrivilegeDescDtos(privilegeDescDtoList);
            productDtoList.add(productDto);
        });
        //返回前端分页数据
        pageSelectDto.setListPageData(productDtoList);
    }

    public List<ProductDto> getProductCarouselList(){
        List<ProductDto> productDtoList=new ArrayList<>();
        ProductExample productExample=new ProductExample();
        ProductExample.Criteria criteria=productExample.createCriteria();
        criteria.andIsShowEqualTo(YesOrNoEnum.YES.getCode());
        criteria.andStatusEqualTo(StatusEnum.PUBLISH.getCode());
        //级别为高级，在显示在产品中心轮播图产品
        criteria.andLevelEqualTo(LevelEnum.THREE.getCode());
        productExample.setOrderByClause("sort asc");
        List<Product> productList=productMapper.selectByExampleWithBLOBs(productExample);
        productList.stream().forEach(product->{
            List<String> picList=new ArrayList<>();
            List<ProductPrivilegeDescDto> privilegeDescDtoList=new ArrayList<>();
            if(!StringUtils.isEmpty(product.getPicList())){
                picList=Arrays.asList(product.getPicList().split(";"));
            }
            if(!StringUtils.isEmpty(product.getPrivilegeDesc())){
                List<String> privilegeDescList=Arrays.asList(product.getPrivilegeDesc().split(";"));
                for(String privilegeDescDto:privilegeDescList){
                    ProductPrivilegeDescDto productPrivilegeDescDto=new ProductPrivilegeDescDto();
                    JSONObject jsonObject=JSONObject.parseObject(privilegeDescDto);
                    productPrivilegeDescDto=JSONObject.toJavaObject(jsonObject,ProductPrivilegeDescDto.class);
                    privilegeDescDtoList.add(productPrivilegeDescDto);
                }
            }

            ProductDto productDto=DuplicateUtil.copy(product,ProductDto.class);
            productDto.setPicList(picList);
            productDto.setProductPrivilegeDescDtos(privilegeDescDtoList);
            productDtoList.add(productDto);
        });
        return productDtoList;
    }
}
